package ch.pizzapp.kurier.adapter;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import ch.pizzapp.kurier.data.PlaceData;
import ch.pizzapp.kurier.view.PlaceListItem;
import ch.pizzapp.kurier.view.PlaceListItem_;

@EBean
public class PlaceAdapter extends BaseAdapter {

	List<PlaceData> placeDataData;
	List<PlaceData> placeDataDataOri;

	@RootContext
	Context context;

	@Override
	public View getView(final int position, final View convertView,
			final ViewGroup parent) {

		PlaceListItem placeListItem;
		if (convertView == null) {
			placeListItem = PlaceListItem_.build(context);
		} else {
			placeListItem = (PlaceListItem) convertView;
		}

		placeListItem.bind(getItem(position));

		placeListItem.setOnCallback(new PlaceListItem.Callback() {

			@Override
			public void clickPlace(PlaceData placeDataItem) {
				// TODO Auto-generated method stub
				if (mCallback != null) {
					mCallback.clickPlace(placeDataItem);
				}
			}
		});

		placeListItem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mCallback.clickPlace(getItem(position));
			}
		});

		return placeListItem;
	}

	public List<PlaceData> getPlaceDataData() {
		return placeDataData;
	}

	public void setPlaceDataData(List<PlaceData> placeDataData) {
		this.placeDataData = placeDataData;
	}

	public List<PlaceData> getPlaceDataDataOri() {
		return placeDataDataOri;
	}

	public void setPlaceDataDataOri(List<PlaceData> placeDataDataOri) {
		placeDataData = new ArrayList<PlaceData>();

		placeDataData.addAll(placeDataDataOri);
		this.placeDataDataOri = placeDataDataOri;
	}

	@Override
	public int getCount() {
		return placeDataDataOri.size();
	}

	@Override
	public PlaceData getItem(final int position) {
		return placeDataDataOri.get(position);
	}

	@Override
	public long getItemId(final int position) {
		return position;
	}

	public void filter(String charText) {
		charText = charText.toLowerCase();
		placeDataDataOri.clear();
		if (charText.length() == 0) {
			placeDataDataOri.addAll(placeDataData);
		} else {
			for (PlaceData wp : placeDataData) {
				if (wp.getTitle().toLowerCase().startsWith(charText)
						|| wp.getZip().toLowerCase().startsWith(charText)) {
					placeDataDataOri.add(wp);
				}
			}
		}
		notifyDataSetChanged();
	}

	public interface Callback {
		void clickPlace(PlaceData placeDataItem);

	}

	Callback mCallback;

	public void setOnCallback(Callback mCallback) {
		this.mCallback = mCallback;
	}

}
